#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

namespace wzy
{
	template<class T>
	struct list_Node
	{
		T _data;
		list_Node* _next;
		list_Node* _prev;

		list_Node(const T& data = T())
			:_data(data)
			,_next(nullptr)
			,_prev(nullptr)
		{
		}


	};

	template<class T,class Ref ,class Ptr>
	struct list_Iterator
	{
		typedef list_Node<T> Node;
		typedef list_Iterator<T,Ref,Ptr> Self;
		
		Node* _node;

		list_Iterator(Node* node)
			:_node(node)
		{
		}

		Ref operator*()
		{
			return _node->_data;
		}

		Ptr operator->()
		{
			return &(_node->_data);
		}

		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}

		Self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}

		bool operator!=(const Self& s) const
		{
			return _node != s._node;
		}

		bool operator==(const Self& s) const
		{
			return _node == s._node;
		}
	};

	template<class T>
	class list
	{
		typedef list_Node<T> Node;
		

		Node* _head;
		size_t _size;
	public:
		typedef list_Iterator<T,T&,T*> iterator;
		typedef list_Iterator<T,const T&,const T*> const_iterator;

		list()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			_size = 0;			
		}

		void push_back(const T& x)
		{
			/*Node* cur = _head->_prev;
			Node* newnode = new Node(x);
			_head->_prev = newnode;
			newnode->_next = _head;
			cur->_next = newnode;
			newnode->_prev = cur;
			++_size;*/
			insert(end(), x);
		}

		void push_front(const T& x)
		{
			insert(begin(), x);
		}

		void insert(iterator pos, const T& x)
		{
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			
			Node* newnode = new Node(x);
			cur->_prev = newnode;
			newnode->_next = cur;
			prev->_next = newnode;
			newnode->_prev = prev;
			++_size;
		}

		void pop_back()
		{
			erase(--end());
		}

		void pop_front()
		{
			erase(begin());
		}

		void erase(iterator pos)
		{
			assert(pos != end());

			Node* next = pos._node->_next;
			Node* prev = pos._node->_prev;
			next->_prev = prev;
			prev->_next = next;
			delete pos._node;
			--_size;
		}

		iterator begin() 
		{
			return _head->_next;
		}

		const_iterator begin() const
		{
			return _head->_next;
		}

		iterator end() 
		{
			return _head;
		}

		const_iterator end() const
		{
			return _head;
		}

	};

	void test_list1()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4); 
		lt.push_back(5); 
		lt.push_back(6);
		lt.push_back(7);
		lt.push_front(20);

		int x = 0;
		cin >> x;
		list<int>::iterator it = lt.begin();
		while (it != lt.end())
		{
			if (*it == x)
				break;
			++it;
		}
		lt.insert(it, 20);

		for (auto e : lt)
		{
			cout << e << " ";
		}
		cout << endl;

		lt.pop_front();

		for (auto e : lt)
		{
			cout << e << " ";
		}
		cout << endl;
	}
}


